// 时间
dayjs.locale('zh-cn');
const headerTimeInit = () => {
  const setTime = () => {
    const headerTime = dayjs().format('HH:mm:ss');
    const headerDate = dayjs().format('dddd YYYY年 MM月 DD日');

    $('#zHeaderTime').text(headerTime);
    $('#zHeaderDate').text(headerDate);
  };
  setTime();

  setInterval(() => {
    setTime();
  }, 1000);
};
headerTimeInit();

// 切换全屏
$('#zFullscreenBtn').on('click', function () {
  let elem = document.querySelector('#app');
  if (!document.fullscreenElement) {
    elem.requestFullscreen().catch((err) => {
      alert(`尝试启用全屏模式时出错：${err.message}（${err.name}）`);
    });
  } else {
    document.exitFullscreen();
  }
});
// fullscreenchange
document.addEventListener('fullscreenchange', () => {
  if (document.fullscreenElement) {
    $('#zFullscreenBtn').addClass('icon-fullscreen-cancel');
  } else {
    $('#zFullscreenBtn').removeClass('icon-fullscreen-cancel');
  }
});

// 中间地图
const mapChart = echarts.init(document.querySelector('#mapChart'));
let mapName = 'china';
let chinaMap; //geo地图
const mapZoom = 1.1;

const mapChartInit = () => {
  const _data = [...hostLocation];
  // 构造散点图数据
  const scatterData = [];
  _data.forEach((item) => {
    const { hostName, lat, lon, count } = item;
    // lon经度 , lat纬度
    scatterData.push({
      value: [lon, lat, count],
      hostName,
    });
  });
  console.log('scatterData', scatterData);

  const mapChartOption = {
    tooltip: {
      trigger: 'item',
    },
    geo: [
      {
        show: true,
        map: mapName,
        zoom: mapZoom,
        itemStyle: {
          borderColor: '#fff',
          borderWidth: 3,
          shadowBlur: 30,
          shadowColor: 'rgba(0,0,0, 0.65)',
          shadowOffsetX: 0,
          shadowOffsetY: 30,
        },
      },
    ],
    series: [
      // 散点（气泡）图
      {
        type: 'effectScatter',
        // scatter 散点（气泡）图
        // effectScatter 带有涟漪特效动画的散点（气泡）图
        coordinateSystem: 'geo',
        data: [...scatterData],
        symbolSize: function (val) {
          // return val[2] / 10;
          return 16;
        },
        label: {
          show: true,
          position: 'right',
          color: 'rgba(255, 224, 52, 0.5)',
          formatter: (param) => {
            const { hostName } = param.data;
            return hostName;
          },
        },
        itemStyle: {
          color: (param) => {
            const { value } = param;
            // TODO 这里条件改下
            if (value[2] > 100) {
              return 'rgba(255, 0, 0, 0.5)';
            }
            return 'rgba(255, 224, 52, 0.5)';
          },
        },
      },
      {
        type: 'map',
        map: mapName,
        name: '中国',
        zoom: mapZoom,
        itemStyle: {
          borderColor: 'rgba(1, 153, 255, 1)',
          borderWidth: 1,
          //渐变背景
          areaColor: 'rgb(0, 78, 162)',
        },
        label: {
          show: true,
          color: 'rgba(255,255,255, 0.3)',
          fontSize: 10,
        },
      },
    ],
  };
  mapChartOption && mapChart.setOption(mapChartOption);
};
const hostLocationInit = async () => {
  await $.ajax({
    url: '../lib/chinaMap.json',
    success: (mapjson) => {
      chinaMap = mapjson;
      echarts.registerMap(mapName, chinaMap); //注册地图
      mapChartInit();
    },
  });
};

// 左侧1 饼图 告警严重性分类
const alarmSeverityClassChart = echarts.init(
  document.querySelector('#alarmSeverityClass')
);

let alarm_angle = 0;
let alarm_timer = null;
const alarmSeverityClassInit = () => {
  const _data = [...alarmSeverity];

  const alarmSeverityClassData = [];
  _data.forEach((item) => {
    const { count: value, severityName: name } = item;
    alarmSeverityClassData.push({
      name,
      value,
    });
  });

  let sum = 0;
  const legendData = [];
  alarmSeverityClassData.forEach((item) => {
    sum += item.value;
    legendData.push(item.name);
  });

  const getPercentage = (data = [], name) => {
    let percentage = 0;
    if (sum <= 0) {
      return percentage;
    }
    for (let index = 0; index < data.length; index++) {
      const item = data[index];
      if (item.name === name) {
        percentage = item.value / sum;
        break;
      }
    }
    return percentage;
  };

  const alarmSeverityClassOption = {
    color: ['#34E4FC', '#67F5B7', '#FFB658', '#E2F7FF'],
    legend: {
      show: false,
      itemWidth: 10,
      itemHeight: 10,
      orient: 'vertical',
      right: 20,
      top: 'middle',
      textStyle: {
        color: 'rgba(255,255,255, 0.8)',
      },
      formatter: (name) => {
        let percentage = getPercentage(alarmSeverityClassData, name);
        percentage = (percentage * 100).toFixed(2);
        return `${name}   ${percentage}%`;
      },
      data: [...legendData],
    },
    series: [
      {
        name: 'circle',
        type: 'pie',
        center: ['25%', '50%'],
        radius: ['75%', '76%'],
        animation: false,
        label: {
          show: false,
        },
        data: [
          {
            name: '1',
            value: 10,
            itemStyle: {
              color: '#fff',
            },
          },
          {
            name: '2',
            value: 10,
            itemStyle: {
              color: '#3b4e64',
            },
          },
          {
            name: '3',
            value: 10,
            itemStyle: {
              color: '#fff',
            },
          },
          {
            name: '4',
            value: 10,
            itemStyle: {
              color: '#3b4e64',
            },
          },
          {
            name: '5',
            value: 10,
            itemStyle: {
              color: '#fff',
            },
          },
          {
            name: '6',
            value: 10,
            itemStyle: {
              color: '#3b4e64',
            },
          },
        ],
      },
      {
        type: 'pie',
        center: ['25%', '50%'],
        radius: ['50%', '65%'],
        animation: false,
        label: {
          show: true,
          position: 'center',
          formatter: (param) => {
            return `{valClass|${sum}}\n{nameClass|总告警数}`;
          },
          rich: {
            valClass: {
              fontFamily: 'D-DIN-PRO',
              fontSize: 24,
              color: '#fff',
              lineHeight: 30,
            },
            nameClass: {
              fontSize: 14,
              color: 'rgba(255,255,255,0.8)',
            },
          },
        },
        data: [...alarmSeverityClassData],
      },
    ],
  };
  alarmSeverityClassChart.setOption(alarmSeverityClassOption);

  // 旋转动画
  alarm_timer && clearInterval(alarm_timer);
  alarm_timer = setInterval(() => {
    alarm_angle += 4;
    if (alarm_angle > 360) {
      alarm_angle = 0;
    }
    alarmSeverityClassChart.setOption({
      series: [
        {
          name: 'circle',
          startAngle: alarm_angle + 90,
        },
      ],
    });
  }, 100);

  //  渲染图例
  let legendHtml = '';
  const colorClass = ['is-blue', 'is-green', 'is-yellow', 'is-white'];
  alarmSeverityClassData.forEach((item, index) => {
    const { name, value } = item;
    let percentage = getPercentage(alarmSeverityClassData, name);
    percentage = (percentage * 100).toFixed(2);
    legendHtml += `
      <div class="legend-item">
        <span class="legend-icon ${colorClass[index]}"></span>
        <span class="legend-label">${name}</span>
        <span class="legend-value">${percentage}%</span>
      </div>
    `;
  });

  $('#chartAlarmSeverityClassLegend').html(legendHtml);
};

// 左侧2 柱状图 主机组告警数（top10）
const pendingIssueLeftChart = echarts.init(
  document.querySelector('#pendingIssueLeft')
);
const pendingIssueLeftInit = () => {
  const _data = [...hostGroupAlarmCount];
  const pendingIssueLeftData = [];
  const pendingIssueLeft_yAxis = [];

  _data.forEach((item) => {
    pendingIssueLeftData.push(item.count);
    pendingIssueLeft_yAxis.push(item.hostGroupName);
  });

  const pendingIssueLeftOption = {
    tooltip: {
      show: true,
      trigger: 'axis',
    },
    grid: {
      top: 36,
      bottom: 20,
      left: 24,
      right: 24,
      containLabel: true,
    },
    xAxis: {
      type: 'value',
      axisLabel: {
        show: false,
      },
      splitLine: {
        show: false,
      },
    },
    yAxis: {
      type: 'category',
      data: [...pendingIssueLeft_yAxis],
      axisLine: {
        lineStyle: {
          color: 'rgba(205, 224, 255, 0.24)',
        },
      },
      axisLabel: {
        color: '#CDE0FF',
      },
      axisTick: {
        show: false,
      },
      interval: 12,
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed',
          color: ['#395e86'],
        },
      },
    },
    series: [
      {
        type: 'bar',
        barMaxWidth: 8,
        data: [...pendingIssueLeftData],
        itemStyle: {
          borderWidth: 1,
          borderColor: '#29B8FF',
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 1,
            y2: 0,
            colorStops: [
              {
                offset: 0,
                color: 'transparent', // 0% 处的颜色
              },
              {
                offset: 1,
                color: 'rgba(41, 221, 255, 0.64)', // 100% 处的颜色
              },
            ],
          },
        },
        label: {
          show: true,
          position: 'right',
          color: '#29DDFF',
        },
      },
    ],
  };
  pendingIssueLeftChart.setOption(pendingIssueLeftOption);
};

// 左侧3 折线图 告警趋势
const alertTrendsChart = echarts.init(document.querySelector('#alertTrends'));
const alertTrendsInit = () => {
  const _data = [...alarmTrend];
  const alertTrendsData = [];
  const alertTrends_xAxis = [];

  _data.forEach((item) => {
    const { count, time } = item;
    const _time = dayjs(time).format('YYYY-M-D H:mm');
    alertTrendsData.push(count);
    alertTrends_xAxis.push(_time);
  });

  const alertTrendsOption = {
    tooltip: {
      show: true,
      trigger: 'axis',
    },
    grid: {
      top: 36,
      bottom: 20,
      left: 24,
      right: 24,
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      axisLabel: {
        color: '#C2D9EB',
      },
      axisTick: {
        show: false,
      },
      axisLine: {
        lineStyle: {
          color: '#51688F',
        },
      },
      data: [...alertTrends_xAxis],
    },
    yAxis: {
      type: 'value',
      name: '条',
      nameTextStyle: {
        align: 'right',
        color: '#C2D9EB',
      },
      axisLabel: {
        color: '#C2D9EB',
      },

      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed',
          color: ['#395e86'],
        },
      },
    },
    series: [
      {
        type: 'line',
        data: [...alertTrendsData],
        itemStyle: {
          color: '#FFDB29',
        },
        lineStyle: {
          width: 1,
        },
        symbolSize: 3,
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(255, 224, 44, 0.16)',
              },
              {
                offset: 1,
                color: 'transparent',
              },
            ],
          },
        },
      },
    ],
  };

  alertTrendsChart.setOption(alertTrendsOption);
};

let hostStatus_angle = 0;
let hostStatus_timer = null;
// 右侧1 主机状态统计
const hostStatusChart = echarts.init(document.querySelector('#hostStatus'));

const hostStatusInit = () => {
  const _data = [...hostStatusCount];

  const hostStatusData = [];

  _data.forEach((item) => {
    const { hostStatus: name, count: value } = item;
    hostStatusData.push({
      name,
      value,
    });
  });

  let sum = 0;
  const legendData = [];
  hostStatusData.forEach((item) => {
    sum += item.value;
    legendData.push(item.name);
  });

  const getPercentage = (data = [], name) => {
    let percentage = 0;
    if (sum <= 0) {
      return percentage;
    }
    for (let index = 0; index < data.length; index++) {
      const item = data[index];
      if (item.name === name) {
        percentage = item.value / sum;
        break;
      }
    }
    return percentage;
  };

  const hostStatusOption = {
    color: ['#34E4FC', '#67F5B7', '#FFB658', '#E2F7FF'],
    legend: {
      show: false,
      itemWidth: 10,
      itemHeight: 10,
      orient: 'vertical',
      right: 20,
      top: 'middle',
      textStyle: {
        color: 'rgba(255,255,255, 0.8)',
      },
      formatter: (name) => {
        let percentage = getPercentage(hostStatusData, name);
        percentage = (percentage * 100).toFixed(2);
        return `${name}   ${percentage}%`;
      },
      data: [...legendData],
    },
    series: [
      {
        name: 'circle',
        type: 'pie',
        center: ['25%', '50%'],
        radius: ['75%', '76%'],
        animation: false,
        label: {
          show: false,
        },
        data: [
          {
            name: '1',
            value: 10,
            itemStyle: {
              color: '#fff',
            },
          },
          {
            name: '2',
            value: 10,
            itemStyle: {
              color: '#3b4e64',
            },
          },
          {
            name: '3',
            value: 10,
            itemStyle: {
              color: '#fff',
            },
          },
          {
            name: '4',
            value: 10,
            itemStyle: {
              color: '#3b4e64',
            },
          },
          {
            name: '5',
            value: 10,
            itemStyle: {
              color: '#fff',
            },
          },
          {
            name: '6',
            value: 10,
            itemStyle: {
              color: '#3b4e64',
            },
          },
        ],
      },
      {
        type: 'pie',
        center: ['25%', '50%'],
        radius: ['50%', '65%'],
        animation: false,
        label: {
          show: true,
          position: 'center',
          formatter: (param) => {
            return `{valClass|${sum}}\n{nameClass|总设备}`;
          },
          rich: {
            valClass: {
              fontFamily: 'D-DIN-PRO',
              fontSize: 24,
              color: '#fff',
              lineHeight: 30,
            },
            nameClass: {
              fontSize: 14,
              color: 'rgba(255,255,255,0.8)',
            },
          },
        },
        data: [...hostStatusData],
      },
    ],
  };
  hostStatusChart.setOption(hostStatusOption);
  // 旋转动画
  hostStatus_timer && clearInterval(hostStatus_timer);
  hostStatus_timer = setInterval(() => {
    hostStatus_angle += 4;
    if (hostStatus_angle > 360) {
      hostStatus_angle = 0;
    }
    hostStatusChart.setOption({
      series: [
        {
          name: 'circle',
          startAngle: hostStatus_angle + 90,
        },
      ],
    });
  }, 100);
  //  渲染图例
  let legendHtml = '';
  const colorClass = ['is-blue', 'is-green', 'is-yellow', 'is-white'];
  hostStatusData.forEach((item, index) => {
    const { name, value } = item;
    let percentage = getPercentage(hostStatusData, name);
    percentage = (percentage * 100).toFixed(2);
    legendHtml += `
      <div class="legend-item">
        <span class="legend-icon ${colorClass[index]}"></span>
        <span class="legend-label">${name}</span>
        <span class="legend-value">${percentage}%</span>
      </div>
    `;
  });

  $('#chartHostStatusLegend').html(legendHtml);
};

// 右侧2 待处理问题主机
const pendingIssueRightChart = echarts.init(
  document.querySelector('#pendingIssueRight')
);
const pendingIssueRightInit = () => {
  const _data = [...pendingAlarmMachine];
  const pendingIssueRightData = [];
  const pendingIssueRight_yAxis = [];
  _data.forEach((item) => {
    const { count, hostName } = item;
    pendingIssueRightData.push(count);
    pendingIssueRight_yAxis.push(hostName);
  });

  const imageDom = document.createElement('img');
  const imageBgDom = document.createElement('img');
  imageDom.src = '../images/pictorialBar.png';
  imageBgDom.src = '../images/pictorialBar_bg.png';
  const pendingIssueRightOption = {
    tooltip: {
      show: true,
      trigger: 'axis',
    },
    grid: {
      top: 36,
      bottom: 20,
      left: 24,
      right: 24,
      containLabel: true,
    },
    xAxis: {
      type: 'value',
      axisLabel: {
        show: false,
      },
      splitLine: {
        show: false,
      },
    },
    yAxis: {
      type: 'category',
      data: [...pendingIssueRight_yAxis],
      axisLabel: {
        color: '#CDE0FF',
      },
      axisTick: {
        show: false,
      },
      interval: 12,
      axisLine: {
        show: false,
      },
    },
    series: [
      {
        type: 'bar',
        barMaxWidth: 6,
        data: [...pendingIssueRightData],
        itemStyle: {
          color: {
            image: imageDom, // 支持为 HTMLImageElement, HTMLCanvasElement，不支持路径字符串
            repeat: 'repeat',
          },
        },
        showBackground: true,
        backgroundStyle: {
          color: {
            image: imageBgDom,
            repeat: 'repeat',
          },
        },
        label: {
          show: true,
          position: 'right',
          color: '#29FFDB',
        },
      },
    ],
  };

  pendingIssueRightChart.setOption(pendingIssueRightOption);
};

// 右侧3 告警问题严重性及问题数量
const severityAlertsChart = echarts.init(
  document.querySelector('#severityAlerts')
);
const severityAlertsInit = () => {
  const _data = [...alarmSeverity];
  const severityAlertsBarData = [];
  const severityAlertsLineData = [];
  const severityAlerts_xAxis = [];

  _data.forEach((item) => {
    const { count, pendingCount, severityName } = item;
    severityAlertsBarData.push(count);
    severityAlertsLineData.push(pendingCount);
    severityAlerts_xAxis.push(severityName);
  });

  const yAxis = {
    type: 'value',
    axisLabel: {
      color: '#C2D9EB',
    },
    splitLine: {
      show: true,
      lineStyle: {
        type: 'dashed',
        color: ['#395e86'],
      },
    },
  };
  const severityAlertsOption = {
    tooltip: {
      show: true,
      trigger: 'axis',
    },
    grid: {
      top: 36,
      bottom: 20,
      left: 24,
      right: 24,
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      axisLabel: {
        color: '#C2D9EB',
        interval: 0, //0 强制显示所有标签
      },
      axisTick: {
        show: false,
      },
      axisLine: {
        lineStyle: {
          color: '#51688F',
        },
      },
      data: [...severityAlerts_xAxis],
    },
    yAxis: [
      {
        // name: '告警数量',
        nameTextStyle: {
          // align: 'right',
          color: '#C2D9EB',
        },
        ...yAxis,
      },
      {
        // name: '待处理数量',
        nameTextStyle: {
          // align: 'right',
          color: '#C2D9EB',
        },
        ...yAxis,
      },
    ],

    series: [
      {
        type: 'bar',
        name: '告警数量',
        data: [...severityAlertsBarData],
        barMaxWidth: 12,
        showBackground: true,
        backgroundStyle: {
          color: 'rgba(8, 129, 194, 0.21)',
          borderColor: 'rgba(10, 108, 194, 0.73)',
          borderWidth: 1,
        },
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(53, 231, 253, 1)',
              },
              {
                offset: 1,
                color: 'rgba(9, 91, 196, 1)',
              },
            ],
          },
        },
      },
      {
        type: 'line',
        name: '待处理数量',
        data: [...severityAlertsLineData],
        yAxisIndex: 1,
        itemStyle: {
          color: '#FFDB29',
        },
        lineStyle: {
          width: 1,
          shadowBlur: 8,
          shadowColor: 'rgba(255, 219, 41, 0.4)',
          shadowOffsetY: 4,
        },
        symbolSize: 3,
        showSymbol: false,
        smooth: true,
      },
    ],
  };
  severityAlertsChart.setOption(severityAlertsOption);
};

// resize
window.addEventListener('resize', () => {
  mapChart?.resize();
  // 左侧
  alarmSeverityClassChart?.resize();
  pendingIssueLeftChart?.resize();
  alertTrendsChart?.resize();
  // 右侧
  hostStatusChart?.resize();
  pendingIssueRightChart?.resize();
  severityAlertsChart?.resize();
});

// 表格滚动
let timerTableScroll = null;
// 表格
const renderPendingAlarmTable = () => {
  let pendingAlarmHtml = '';

  let severityTagMap = [
    'theme-undefined', // 未定义
    'theme-info', // 信息
    'theme-warning', //警告
    'theme-general', // 一般
    'theme-serious', //严重
    'theme-disaster', // 灾难
  ];
  pendingAlarmTableData.forEach((item, index) => {
    const { time, host, name, pName, severity, severityName } = item;
    const _time = dayjs(time).format('YYYY-MM-DD');
    pendingAlarmHtml += `
      <tr>
        <td><div class="cell">${_time}</div></td>
        <td><div class="cell">${host}</div></td>
        <td><div class="cell">${name}</div></td>
        <td><div class="cell">${pName}</div></td>
        <td>
          <div class="cell">
            <span class="severity-tag ${severityTagMap[severity]}">${severityName}</span>
          </div>
        </td>
      </tr>
  `;
  });

  const $tableScroll = $('#tableScroll');
  const $tbody = $('#pendingAlarmTable');
  $tbody.html(pendingAlarmHtml);

  // 开启表格滚动
  timerTableScroll && clearInterval(timerTableScroll);
  let current = 0;
  timerTableScroll = setInterval(() => {
    // 获取wrap的高度, 获取每一行的高度
    const wrapH = $tableScroll.outerHeight();
    const tbodyH = $tbody.outerHeight();
    const trLength = $tbody.find('tr').length;
    if (tbodyH <= wrapH || trLength <= 0) {
      clearInterval(timerTableScroll);
      return;
    }
    const trH = tbodyH / trLength;
    const max = trLength - Math.floor(wrapH / trH);
    let scrollTop = current * trH;
    $tableScroll.scrollTop(scrollTop);
    current++;
    if (current >= max) {
      current = 0;
    }
  }, 3000);
};

/**
 *
 */
// 主机数量
const hostCountInit = () => {
  const { count } = hostCount;
  $('#hostCount').text(count);
};
// 监控失效主机
const disMonitoredHostCountInit = () => {
  const { count } = disMonitoredHostCount;
  $('#disMonitoredHostCount').text(count);
};
// 未归类主机
const unsortedHostCountInit = () => {
  const { count } = unsortedHostCount;
  $('#unsortedHostCount').text(count);
};
// 主机组数量
const hostGroupCountInit = () => {
  const { count } = hostGroupCount;
  $('#hostGroupCount').text(count);
};
/**
 *
 */
// 告警主机组数
const hostAlarmCountInit = () => {
  const { count } = hostAlarmCount;
  $('#hostAlarmCount').text(count);
};
// 待处理告警数
const pendingAlarmCountInit = () => {
  const { count } = pendingAlarmCount;
  $('#pendingAlarmCount').text(count);
};
// 监控服务机数量
const monitorServerCountInit = () => {
  const { count } = monitorServerCount;
  $('#monitorServerCount').text(count);
};
// 已处理告警数
const solvedAlarmCountInit = () => {
  const { count } = solvedAlarmCount;
  $('#solvedAlarmCount').text(count);
};

/**
 * 拓扑图
 */

const cytoscapeMapInit = () => {
  // 你提供的 JSON 数据
  const mapData = { ...cytoscapeMapData };

  // 解析节点元素，转换成 Cytoscape 格式
  const cyElements = [];

  // 辅助函数：拼接标签多行文本
  function joinLabels(labelArray) {
    return labelArray.map((l) => l.content).join('\n');
  }

  mapData.elements.forEach((el) => {
    // 解析节点颜色（取最后一个标签的fill属性作为颜色）
    let fillColor = '#009900'; // 默认绿色
    for (let i = el.label.length - 1; i >= 0; i--) {
      if (el.label[i].attributes && el.label[i].attributes.fill) {
        fillColor = el.label[i].attributes.fill;
        break;
      }
    }

    cyElements.push({
      data: { id: el.selementid, label: joinLabels(el.label) },
      position: { x: parseInt(el.x), y: parseInt(el.y) },
      style: {
        'background-color': fillColor,
        'color': '#fff',
        'text-wrap': 'wrap',
        'text-max-width': 120,
        'text-valign': 'center',
        'text-halign': 'center',
        'font-size': 12,
        'width': 80,
        'height': 80,
        'shape': 'roundrectangle',
        'border-color': '#333',
        'border-width': 1,
      },
    });
  });

  // 如果有连接线，也可以解析，这里为空
  mapData.links.forEach((link) => {
    cyElements.push({
      data: {
        id: 'link' + link.id,
        source: link.selementid1,
        target: link.selementid2,
      },
    });
  });

  const cy = cytoscape({
    container: document.getElementById('cy'),
    elements: cyElements,
    style: [
      {
        selector: 'node',
        style: {
          'label': 'data(label)',
          'background-color': 'data(style.background-color)',
          'color': 'data(style.color)',
          'text-wrap': 'wrap',
          'text-valign': 'center',
          'text-halign': 'center',
          'font-size': 12,
          'width': 80,
          'height': 80,
          'shape': 'roundrectangle',
          'border-color': '#333',
          'border-width': 1,
        },
      },
      {
        selector: 'edge',
        style: {
          'width': 3,
          'line-color': '#ccc',
          'target-arrow-color': '#ccc',
          'target-arrow-shape': 'triangle',
          'curve-style': 'bezier',
        },
      },
    ],
    layout: {
      name: 'preset', // 使用预设的坐标，不自动布局
    },
  });
};

// tab切换
let tabActive = '0';
$('#zMainTab .z-main-tab-item').on('click', function () {
  const _tabActive = $(this)[0].dataset.id;
  console.log(' _tabActive', _tabActive);
  if (tabActive === _tabActive) {
    return;
  }
  tabActive = _tabActive;
  const $tabs = $('#zMainTab .z-main-tab-item');
  $tabs.removeClass('is-active');
  $(this).addClass('is-active');

  // 渲染地图
  if (tabActive === '0') {
    $('#cy').hide();
    $('#mapChart').show();
    mapChartInit();
  }
  // 渲染拓扑图
  if (tabActive === '1') {
    // 销毁
    mapChart?.clear();
    $('#mapChart').hide();
    $('#cy').show();

    /**
     * 拓扑图
     */
    cytoscapeMapInit();
  }
});

window.addEventListener('resize', () => {
  cytoscapeMapInit();
});
